package com.koron.sinoprobe.web.engineering.excel;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;

/**
 * @author jzp
 * @since 2021/12/8
 */
public class SpDivisionProjectSheetWriteHandler implements SheetWriteHandler {

    private CellStyle readCellStyle;
    private Drawing<?> drawingPatriarch;
    private XSSFClientAnchor xssfClientAnchor = new XSSFClientAnchor(0, 0, 0, 0, 0, 0, 0, 0);
    private ExcelError excelError;

    public SpDivisionProjectSheetWriteHandler(ExcelError excelError){
        this.excelError = excelError;
    }

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        Sheet sheet = writeSheetHolder.getSheet();
        if (readCellStyle == null) {
            drawingPatriarch = sheet.createDrawingPatriarch();
            CellStyle cellStyle = writeSheetHolder.getParentWriteWorkbookHolder().getWorkbook().createCellStyle();
            cellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
            // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND
            cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            this.readCellStyle = cellStyle;
        }
        int rowIndex = excelError.getRowIndex()+1;
        int collIndex = excelError.getCollIndex();
        String comment = excelError.getComment();
        drawComment(sheet.getRow(rowIndex).getCell(collIndex), rowIndex, comment, true);
    }

    /**
     * 给单元格打上备注信息
     */
    private void drawComment(Cell cell, Integer rowIndex, String comment, boolean isStyle) {
        int columnIndex = cell.getColumnIndex();
        Comment cellComment = cell.getCellComment();
        if (cellComment == null) {
            xssfClientAnchor.setCol1(columnIndex);
            xssfClientAnchor.setCol2(columnIndex + 2);
            xssfClientAnchor.setRow1(rowIndex);
            xssfClientAnchor.setRow2(rowIndex + 2);
            cellComment = drawingPatriarch.createCellComment(xssfClientAnchor);
        } else if (cellComment.getString() != null){
            comment = cellComment.getString().getString() + "；"+ comment;
        }

        cellComment.setString(new XSSFRichTextString(comment));
        cell.setCellComment(cellComment);
        if (isStyle) {
            cell.setCellStyle(this.readCellStyle);
        }
    }
}
